package com.liting.uitest.utils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Component
public class FileUtil {

    private static String fileUpload;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @PostConstruct
    public void getUploadFolder() {
        fileUpload = this.uploadFolder;
    }

    /**
     * 获取文件上传的数据
     *
     * @param pic1
     * @param images
     * @return
     */
    public static String getUploadDate(MultipartFile pic1, String images) throws Exception {

        //如果文件夹不存在则创建
        File file = new File(fileUpload + "/" + images);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }

        String filename = pic1.getOriginalFilename();
        String ext1 = filename.substring(filename.lastIndexOf(".") + 1);
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format1 = df.format(new Date());

        try {
            pic1.transferTo(new File(fileUpload + "/" + images + "/" + format1 + "." + ext1));
        } catch (IllegalStateException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        }
        // 返回文件地址
        return images + "/" + format1 + "." + ext1;
    }

    /*
    返回图片绝对路径
     */
    public static String getFilePath(String fileUrl) {
        return fileUpload + "/" + fileUrl;
    }
}

